import MinRequest from '@/utils/MinRequest.js'

const minRequest = new MinRequest()

let loginLock = false

// 请求拦截器
minRequest.interceptors.request((request) => {
	const userInfo = uni.getStorageSync('userInfo') 
	// debugger
	if(userInfo){
		request.header['X-Token'] = userInfo.token
	}
	console.log("请求拦截:" + JSON.stringify(request));
	return request
})

// 响应拦截器
minRequest.interceptors.response((response) => {
	// console.log("响应拦截:" + JSON.stringify(response));
	if(response.data.code == 100004 && !loginLock){
		loginLock = true
		uni.showModal({
		  title: '登录提示',
		  content: '您尚未登录，是否立即登录？',
		  showCancel: true,
		  confirmText: '登录',
		  success: (e) => {
		    if (e.confirm) {
				loginLock = false
		      uni.navigateTo({
		        url: '/pages/public/login'
		      })
		    }
		  },
		  fail: () => {
			  loginLock = false
		  },
		  complete: () => {
			  loginLock = false
		  }
		})
		return;
	}
	return response.data
})

export default {
	// 这里统一管理api请求
	apis: {
		//登录后设置x-token
		settingRequestHeader(data) {
			minRequest.setConfig((config) => {
				// debugger
				config.header = {
					'X-Token': data.token
				}
				return config
			})

		},
		logout() { //注销后清空header 并删除用户信息
			minRequest.setConfig((config) => {
				config.header = {
					'X-Token': null
				}
				return config
			})
			uni.clearStorageSync()
		},

		//登录
		getLoginInfo(data, options) {
			return minRequest.post('/api/appUserLogin', data, options)
		},
		//保存/修改溯源信息
		saveFieldTrace(data, id, options) {
			return minRequest.post('/api/standard/saveApplicationValueList'+id, data, options)
		},
		//查询订单
		searchOrder(data) {
			return minRequest.get('/computer/orderDetails/list', data)
		},
		//查询订单快递
		getExpressage(data) {
			return minRequest.get('/sf/order/list', data)
		},
	}
}

